<template>
  <div class="grades-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>成绩查询</span>
          <el-select
            v-model="currentSemester"
            placeholder="选择学期"
            style="width: 180px"
            @change="handleSemesterChange"
          >
            <el-option
              v-for="item in commonStore.semesters"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </template>
      
      <div class="grade-stats-container" v-loading="loading">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card shadow="hover">
              <template #header>
                <div class="stat-header">
                  <span>平均成绩</span>
                </div>
              </template>
              <div class="stat-number">{{ currentStats.averageScore || 0 }}</div>
              <div class="stat-description">
                <el-progress 
                  :percentage="(currentStats.averageScore / 100) * 100 || 0" 
                  :stroke-width="10"
                  :color="getGradeColor(currentStats.averageScore)"
                />
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover">
              <template #header>
                <div class="stat-header">
                  <span>通过课程</span>
                </div>
              </template>
              <div class="stat-number">{{ currentStats.passedCourses || 0 }} / {{ currentStats.totalCourses || 0 }}</div>
              <div class="stat-description">
                <el-progress 
                  :percentage="currentStats.totalCourses ? (currentStats.passedCourses / currentStats.totalCourses) * 100 : 0" 
                  :stroke-width="10"
                  :color="'#67C23A'"
                />
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover">
              <template #header>
                <div class="stat-header">
                  <span>已修学分</span>
                </div>
              </template>
              <div class="stat-number">{{ currentStats.earnedCredits || 0 }}</div>
              <div class="stat-description">
                <span>本学期课程总学分: {{ currentStats.totalCredits || 0 }}</span>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <div class="grades-table-container">
        <el-table
          :data="currentGrades"
          style="width: 100%"
          :row-class-name="tableRowClassName"
          v-loading="loading"
        >
          <el-table-column prop="courseCode" label="课程代码" width="120" />
          <el-table-column prop="courseName" label="课程名称" min-width="200" />
          <el-table-column prop="credit" label="学分" width="80" align="center" />
          <el-table-column prop="courseType" label="课程类型" width="120" />
          <el-table-column prop="examType" label="考核方式" width="120" />
          <el-table-column label="成绩" width="100" align="center">
            <template #default="scope">
              <span :class="{ 'failed-grade': (scope.row.grade || scope.row.score || 0) < 60 }">
                {{ scope.row.grade || scope.row.score || 0 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="gradePoint" label="绩点" width="80" align="center" />
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-button 
                link
                type="primary" 
                @click="showGradeDetail(scope.row)"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    
    <!-- 成绩详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="成绩详情"
      width="600px"
    >
      <template #header>
        <div class="detail-header">
          <h3>{{ currentCourse.courseName }}</h3>
          <div class="course-code">{{ currentCourse.courseCode }}</div>
        </div>
      </template>
      
      <el-descriptions :column="2" border>
        <el-descriptions-item label="课程名称">{{ currentCourse.courseName }}</el-descriptions-item>
        <el-descriptions-item label="课程代码">{{ currentCourse.courseCode }}</el-descriptions-item>
        <el-descriptions-item label="学分">{{ currentCourse.credit }}</el-descriptions-item>
        <el-descriptions-item label="课程类型">{{ currentCourse.courseType }}</el-descriptions-item>
        <el-descriptions-item label="考核方式">{{ currentCourse.examType }}</el-descriptions-item>
        <el-descriptions-item label="任课教师">{{ currentCourse.teacher }}</el-descriptions-item>
      </el-descriptions>
      
      <div class="grade-detail-container">
        <h4>成绩组成</h4>
        <el-table :data="currentCourse.gradeComponents || []" border style="width: 100%">
          <el-table-column prop="name" label="评分项" width="180" />
          <el-table-column prop="percentage" label="比例" width="100">
            <template #default="scope">
              {{ scope.row.percentage }}%
            </template>
          </el-table-column>
          <el-table-column prop="score" label="得分" width="100" />
          <el-table-column prop="weightedScore" label="加权分" width="100">
            <template #default="scope">
              {{ calculateWeightedScore(scope.row) }}
            </template>
          </el-table-column>
        </el-table>
        
        <div class="final-grade">
          <div class="grade-item">
            <span class="grade-label">最终成绩:</span>
            <span class="grade-value" :class="{ 'failed-grade': (currentCourse.grade || currentCourse.score || 0) < 60 }">
              {{ currentCourse.grade || currentCourse.score || 0 }}
            </span>
          </div>
          <div class="grade-item">
            <span class="grade-label">绩点:</span>
            <span class="grade-value">{{ currentCourse.gradePoint || 0 }}</span>
          </div>
        </div>
        
        <div v-if="currentCourse.teacherComment" class="teacher-comment">
          <h4>教师评语</h4>
          <p>{{ currentCourse.teacherComment }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { studentApi } from '@/api'
import { useRequest } from '@/hooks/useRequest'
import { useCommonStore } from '@/stores/common'
import { ensureArray } from '@/utils/validator'

// 从Pinia获取通用状态
const commonStore = useCommonStore()

// 当前学期
const currentSemester = ref('')

// 成绩数据
const gradesData = ref({})

// 使用useRequest钩子获取成绩数据
const { loading, error, execute: fetchGradesData } = useRequest(studentApi.getGrades)

// 获取成绩数据
const fetchGrades = async () => {
  if (!currentSemester.value) return
  
  try {
    // 获取成绩数据
    const response = await fetchGradesData({ semester: currentSemester.value })
    
    // 处理不同的响应格式
    let data = null
    
    // 情况1: 标准API响应格式 { code: 200, data: {...} }
    if (response && response.code === 200 && response.data) {
      data = response.data
      console.log('成功获取成绩数据(标准格式):', data)
    } 
    // 情况2: 直接返回数据 { grades: [...], stats: {...} }
    else if (response && response.grades && response.stats) {
      data = response
      console.log('成功获取成绩数据(直接格式):', data)
    }
    // 情况3: 其他格式，尝试适配
    else if (response) {
      // 如果返回的是数组，假设是成绩列表
      if (Array.isArray(response)) {
        data = {
          grades: response,
          stats: calculateStats(response)
        }
      } else {
        console.warn('未知的数据格式:', response)
        data = response // 尝试直接使用
      }
      console.log('成功获取成绩数据(适配格式):', data)
    }
    
    if (data) {
      // 更新成绩数据
      gradesData.value = {
        ...gradesData.value,
        [currentSemester.value]: data
      }
    } else {
      console.error('获取成绩数据失败: 无效的数据格式', response)
      ElMessage.error('获取成绩数据失败: 无效的数据格式')
    }
  } catch (error) {
    console.error('获取成绩数据失败:', error)
    ElMessage.error('获取成绩数据失败: ' + (error.message || '未知错误'))
  }
}

// 计算统计数据
const calculateStats = (grades) => {
  if (!grades || !Array.isArray(grades) || grades.length === 0) {
    return {
      totalCredits: 0,
      earnedCredits: 0,
      passedCourses: 0,
      totalCourses: 0,
      averageScore: 0,
      gpa: 0
    }
  }
  
  // 计算总课程数
  const totalCourses = grades.length
  
  // 计算总学分
  const totalCredits = grades.reduce((sum, grade) => sum + (grade.credit || 0), 0)
  
  // 计算已修学分和通过课程数
  const passedGrades = grades.filter(grade => (grade.grade || 0) >= 60)
  const passedCourses = passedGrades.length
  const earnedCredits = passedGrades.reduce((sum, grade) => sum + (grade.credit || 0), 0)
  
  // 计算平均分
  const totalScore = grades.reduce((sum, grade) => sum + (grade.grade || 0), 0)
  const averageScore = totalCourses > 0 ? (totalScore / totalCourses).toFixed(1) : 0
  
  // 计算GPA
  const totalGpaPoints = grades.reduce((sum, grade) => {
    const score = grade.grade || 0
    let gpaPoint = 0
    if (score >= 90) gpaPoint = 4.0
    else if (score >= 85) gpaPoint = 3.7
    else if (score >= 80) gpaPoint = 3.3
    else if (score >= 75) gpaPoint = 3.0
    else if (score >= 70) gpaPoint = 2.7
    else if (score >= 65) gpaPoint = 2.3
    else if (score >= 60) gpaPoint = 2.0
    else gpaPoint = 0
    
    return sum + gpaPoint * (grade.credit || 0)
  }, 0)
  
  const gpa = totalCredits > 0 ? (totalGpaPoints / totalCredits).toFixed(2) : 0
  
  return {
    totalCredits,
    earnedCredits,
    passedCourses,
    totalCourses,
    averageScore,
    gpa
  }
}

// 计算绩点函数
const calculateGradePoint = (grade) => {
  if (grade >= 90) return 4.0
  if (grade >= 85) return 3.7
  if (grade >= 80) return 3.3
  if (grade >= 75) return 3.0
  if (grade >= 70) return 2.7
  if (grade >= 65) return 2.3
  if (grade >= 60) return 2.0
  return 0
}

// 获取学期列表
const fetchSemesters = async () => {
  await commonStore.fetchSemesters()
  
  // 如果没有当前学期，则设置为第一个学期
  if (!currentSemester.value && commonStore.semesters.length > 0) {
    currentSemester.value = commonStore.semesters[0].value
  }
  
  // 获取成绩数据
  fetchGrades()
}

// 当前学期的成绩数据
const currentGradesData = computed(() => {
  if (!currentSemester.value || !gradesData.value[currentSemester.value]) {
    return {
      grades: [],
      stats: {
        totalCredits: 0,
        completedCredits: 0,
        gpa: 0,
        averageScore: 0,
        passRate: 0,
        excellentRate: 0
      }
    }
  }
  return gradesData.value[currentSemester.value]
})

// 处理学期变化
const handleSemesterChange = () => {
  fetchGrades()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchSemesters()
})

// 成绩详情对话框控制
const showDetailDialog = ref(false)
const currentCourse = ref({})

// 当前学期的成绩
const currentGrades = computed(() => {
  if (!currentSemester.value || !gradesData.value[currentSemester.value]) {
    return []
  }
  return gradesData.value[currentSemester.value].grades || []
})

// 当前学期的统计数据
const currentStats = computed(() => {
  if (!currentSemester.value || !gradesData.value[currentSemester.value]) {
    return {
      averageScore: 0,
      passedCourses: 0,
      totalCourses: 0,
      earnedCredits: 0,
      totalCredits: 0,
      gpa: 0
    }
  }
  return gradesData.value[currentSemester.value].stats || {}
})

// 表格行样式
const tableRowClassName = ({ row }) => {
  if (row.grade < 60) {
    return 'failed-row'
  }
  return ''
}

// 获取成绩颜色
const getGradeColor = (grade) => {
  if (grade >= 90) return '#67C23A'
  if (grade >= 80) return '#409EFF'
  if (grade >= 70) return '#E6A23C'
  if (grade >= 60) return '#F56C6C'
  return '#909399'
}

// 显示成绩详情
const showGradeDetail = (course) => {
  // 直接使用课程对象，mock数据已经包含所有必要字段
  currentCourse.value = course
  showDetailDialog.value = true
}

// 计算加权分
const calculateWeightedScore = (component) => {
  return (component.score * component.percentage / 100).toFixed(1)
}
</script>

<style scoped>
.grades-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.grade-stats-container {
  margin-bottom: 30px;
}

.stat-header {
  font-size: 14px;
  color: #606266;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin: 15px 0;
  color: #303133;
}

.stat-description {
  color: #909399;
  font-size: 14px;
}

.grades-table-container {
  margin-top: 20px;
}

.failed-grade {
  color: #F56C6C;
  font-weight: bold;
}

.detail-header {
  text-align: center;
  padding-bottom: 10px;
}

.detail-header h3 {
  margin-bottom: 5px;
  color: #303133;
}

.course-code {
  color: #909399;
  font-size: 14px;
}

.grade-detail-container {
  margin-top: 20px;
}

.grade-detail-container h4 {
  margin: 15px 0;
  color: #303133;
}

.final-grade {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 30px;
}

.grade-item {
  display: flex;
  align-items: center;
}

.grade-label {
  margin-right: 10px;
  font-weight: bold;
}

.grade-value {
  font-size: 18px;
  font-weight: bold;
}

.teacher-comment {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.teacher-comment p {
  margin: 0;
  color: #606266;
}

:deep(.failed-row) {
  background-color: rgba(245, 108, 108, 0.1);
}
</style> 